﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Exam_Server.childForms;
using ExamCommon;
using ExamServerBLL;
using HZH_Controls.Forms;

namespace Exam_Server
{
    public partial class FrmMainServer : Form
    {
        // 定义一个server端的委托集合, 用于 UserService 控制ui
        private static List<Action<string>> userServiceActions = new List<Action<string>>();
        // 临时button引用
        private Button tempButton = null;
        // 配置信息
        private static ServerConfiguration configuration = null;

        public FrmMainServer()
        {
            InitializeComponent();
            panel_initialize();
            userServiceActions.Add(ShowUserLoginInfo); // userServiceActions[0]用于显示用户登录成功窗体
            UserService.initAction(userServiceActions);
            openChildForm(GenerateSingletonFrm<FrmHome>.CreateInstrance());
        }

        /// <summary>
        /// 窗体加载时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMainServer_Load(object sender, EventArgs e)
        {
            // 加载时候应用配置信息
            applyConfig();
        }

        //拖动控件窗体
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;

        //拖动窗体
        private void panelTitleBar_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }

        // 初始化面板
        private void panel_initialize()
        {
            panel_QuestionBank.Visible = false;
            panel_Exercise.Visible = false;
            panel_Examination.Visible = false;
        }

        // 隐藏子菜单
        private void hideSubMenu()
        {
            if (panel_Exercise.Visible == true)
                panel_Exercise.Visible = false;
            if (panel_Examination.Visible == true)
                panel_Examination.Visible = false;
            if (panel_QuestionBank.Visible == true)
                panel_QuestionBank.Visible = false;
        }

        // 显示子菜单
        private void showSubMenu(Panel SubMenu)
        {
            if (SubMenu == null)  //避免空指针异常
            {
                hideSubMenu();
                return;
            }
            if (SubMenu.Visible == false)
            {
                hideSubMenu();
                SubMenu.Visible = true;
            }
            else
            {
                SubMenu.Visible = false;
            }
        }

        // 关闭窗口
        private void btn_close_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        // 最小化窗口
        private void btn_min_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
        }

        // 最大化窗口
        private void btn_max_Click(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Maximized)
            {
                WindowState = FormWindowState.Normal;
            }
            else
            {   //最大化不会覆盖系统状态栏
                MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
                WindowState = FormWindowState.Maximized;
            }
        }

        // 打开子窗体
        private void openChildForm(Form childForm)
        {
            foreach (Control item in this.panelDesktop.Controls)
            {
                if (item is Form)
                {
                    if (childForm == item)
                    {
                        break;
                    }
                    else
                    {
                        Form frm = (Form)item;
                        frm.Close();
                        frm.Dispose();
                        frm = null;
                    }
                }
            }
            childForm.TopLevel = false; // 设置非顶级控件
            childForm.Parent = this.panelDesktop; // 父级容器
            childForm.FormBorderStyle = FormBorderStyle.None; // 去除边框
            childForm.Dock = DockStyle.Fill; // 全覆盖
            childForm.Show();
        }

        // 选中后更改按钮颜色
        private void changeButtonBackColor(Button button)
        {
            if (tempButton != null)
            {
                tempButton.BackColor = Color.FromArgb(55, 55, 55);
            }
            if (button != null)
            {
                tempButton = button;
                tempButton.BackColor = Color.FromArgb(75, 75, 75);
            }
        }

        /// <summary>
        /// 首页logo点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox_logo_Click(object sender, EventArgs e)
        {
            openChildForm(GenerateSingletonFrm<FrmHome>.CreateInstrance());
            showSubMenu(null);
            changeButtonBackColor(null);
            this.label_currentPosition.Text = "当前位置: 首页";
        }

        // 题库管理 按钮点击事件
        private void btn_QBankManage_Click(object sender, EventArgs e)
        {
            showSubMenu(panel_QuestionBank);
        }

        // 考试管理 按钮点击事件
        private void btn_ExamManage_Click(object sender, EventArgs e)
        {
            showSubMenu(panel_Examination);
        }

        // 练习管理 按钮点击事件
        private void btn_Exercise_Click(object sender, EventArgs e)
        {
            showSubMenu(panel_Exercise);
        }

        // 考生管理 按钮点击事件
        private void btn_Examinee_Click(object sender, EventArgs e)
        {
            openChildForm(GenerateSingletonFrm<FrmExaminee>.CreateInstrance());
            showSubMenu(null);
            changeButtonBackColor(btn_Examinee);
            this.label_currentPosition.Text = "当前位置: 考生管理";
        }

        // 系统设置 按钮点击事件
        private void btn_Setting_Click(object sender, EventArgs e)
        {
            FrmSetting frm = GenerateSingletonFrm<FrmSetting>.CreateInstrance();
            frm.ApplyConfig += applyConfig;
            openChildForm(frm);
            showSubMenu(null);
            changeButtonBackColor(btn_Setting);
            this.label_currentPosition.Text = "当前位置: 系统管理";
        }

        private void ShowUserLoginInfo(string s)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    ShowLoginTips(s);
                }));
            }
        }
        /// <summary>
        /// 显示用户登录气泡提示
        /// </summary>
        /// <param name="str"></param>
        private void ShowLoginTips(string str)
        {
            if (configuration.IsShowOnlineBubble) // 读取配置信息
            {
                FrmTips.ShowTips(this, str, 3000, false, ContentAlignment.BottomRight, null, TipsSizeMode.Small, null, TipsState.Info);
                FrmTips.ReshowTips();
            }
        }

        /// <summary>
        /// 显示屏幕上方中部气泡提示信息
        /// </summary>
        /// <param name="str"></param>
        private void ShowTopTips(string str)
        {
            FrmTips.ShowTips(this, str, 3000, false, ContentAlignment.TopCenter, null, TipsSizeMode.Small, null, TipsState.Success);
            FrmTips.ReshowTips();
        }

        // 关闭按钮移入事件
        private void btn_close_MouseEnter(object sender, EventArgs e)
        {
            this.btn_close.BackColor = Color.FromArgb(245, 108, 108);
        }
        // 关闭按钮移出事件
        private void btn_close_MouseLeave(object sender, EventArgs e)
        {
            this.btn_close.BackColor = Color.FromArgb(34, 34, 37);
        }
        // 试题管理
        private void btn_TestQuestion_Click(object sender, EventArgs e)
        {
            openChildForm(GenerateSingletonFrm<FrmTestQuestion>.CreateInstrance());
            changeButtonBackColor(btn_TestQuestion);
            this.label_currentPosition.Text = "当前位置: 题库管理 > 试题管理";
        }
        // 题库管理
        private void btn_QuestionBank_Click(object sender, EventArgs e)
        {
            openChildForm(GenerateSingletonFrm<FrmQusetionBank>.CreateInstrance());
            changeButtonBackColor(btn_QuestionBank);
            this.label_currentPosition.Text = "当前位置: 题库管理 > 题库管理";
        }

        // 试卷管理
        private void btn_ExamPaper_Click(object sender, EventArgs e)
        {
            openChildForm(GenerateSingletonFrm<FrmExamPaper>.CreateInstrance());
            changeButtonBackColor(btn_ExamPaper);
            this.label_currentPosition.Text = "当前位置: 考试管理 > 试卷管理";
        }

        // 考试管理
        private void btn_Examination_Click(object sender, EventArgs e)
        {
            openChildForm(GenerateSingletonFrm<FrmEaxmination>.CreateInstrance());
            changeButtonBackColor(btn_Examination);
            this.label_currentPosition.Text = "当前位置: 考试管理 > 考试管理";
        }

        // 智能阅卷
        private void btn_Marking_Click(object sender, EventArgs e)
        {
            openChildForm(GenerateSingletonFrm<FrmMarking>.CreateInstrance());
            changeButtonBackColor(btn_Marking);
            this.label_currentPosition.Text = "当前位置: 考试管理 > 智能阅卷";
        }

        // 统计分析
        private void btn_Statistic_Click(object sender, EventArgs e)
        {
            openChildForm(GenerateSingletonFrm<FrmStatistic>.CreateInstrance());
            changeButtonBackColor(btn_Statistic);
            this.label_currentPosition.Text = "当前位置: 考试管理 > 统计分析";
        }

        // 习题册管理
        private void btn_ExerciseBook_Click(object sender, EventArgs e)
        {
            openChildForm(GenerateSingletonFrm<FrmExerciseBook>.CreateInstrance());
            changeButtonBackColor(btn_ExerciseBook);
            this.label_currentPosition.Text = "当前位置: 练习管理 > 习题册管理";
        }

        // 发布练习
        private void btn_PublishExercise_Click(object sender, EventArgs e)
        {
            openChildForm(GenerateSingletonFrm<FrmPublishExercise>.CreateInstrance());
            changeButtonBackColor(btn_PublishExercise);
            this.label_currentPosition.Text = "当前位置: 练习管理 > 发布练习";
        }


        // 时间显示
        private void timer_time_Tick(object sender, EventArgs e)
        {
            DateTime time = System.DateTime.Now;
            string TimePattern = configuration.TimePattern; // 时间格式读取配置信息
            label_Time.Text = "时间: " + time.ToString(TimePattern);
        }

        /// <summary>
        /// 应用配置
        /// </summary>
        private void applyConfig()
        {
            // 读取配置信息
            configuration = ServerConfiguration.ReadConfiguration();
            // 读取配置信息失败,将初始化配置信息
            if (configuration == null)
            {
                FrmDialog.ShowDialog(this, "错误原因: 读取配置信息时发生错误!\n即将执行: 重置配置信息!", "初始化错误");
                // 重置默认配置文件
                ServerConfiguration config = new ServerConfiguration();
                bool flag = ServerConfiguration.WriteConfiguration(config);
                if (flag)
                {
                    ShowTopTips("重置配置信息成功!");
                }
                // 再次读取配置信息
                configuration = ServerConfiguration.ReadConfiguration();
            }
            // 时间显示
            if (configuration.IsShowTime)
            {
                this.panel_Time.Visible = true;
                timer_time.Start(); // 开始
            }
            else
            {
                this.panel_Time.Visible = false;
                timer_time.Stop();  // 停止
            }
            // 判断socket服务状态
            bool isOpen = GenerateSingletonFrm<FrmSetting>.CreateInstrance().GetSocketServiceStatus();
            // ip地址和端口号
            if (configuration.IsShowIpAndPort)
            {
                this.panel_IpAndPort.Visible = true;
                // 获取本机IP地址
                string ipAdd = string.Empty;
                //string ipAdd = NetHelper.GetLocalIp();    //获取一个随机IP地址
                if (configuration.IsShowAllIp)
                {
                    ipAdd = NetHelper.GetAllIP();      // 获取所有网卡IP地址(包括虚拟网卡ip地址)
                }
                else
                {
                    ipAdd = NetHelper.GetPhysicalIP();   // 获取真实网卡IP地址(可能不止一个)
                }
                string portStr = string.Empty;

                if (isOpen)
                {
                    portStr = configuration.SocketPort.ToString();
                }
                else
                {
                    portStr = "未监听";
                }

                string ipStr = "服务IP地址: " + ipAdd + "   端口号: " + portStr;
                this.label_IpAndPort.Text = ipStr;
            }
            else
            {
                this.panel_IpAndPort.Visible = false;
            }
            ChangeScoketStatus(isOpen);
            // 在线人数, 考试人数 是否可见
            this.panel_OnlineNum.Visible = configuration.IsShowOnlineNum;
            this.panel_ExamNum.Visible = configuration.IsShowExamNum;
        }

        private void ChangeScoketStatus(bool isOpen)
        {
            if (isOpen)
            {
                // 修改状态值
                this.label_ConnectServiceStatus.Text = "已开启";
                this.label_ConnectServiceStatus.ForeColor = Color.FromArgb(60, 179, 113);
            }
            else
            {
                this.label_ConnectServiceStatus.Text = "已关闭";
                this.label_ConnectServiceStatus.ForeColor = Color.Orange;
            }
        }
    }
}
